#admin/jira/approval_route.py
from datetime import datetime
from flask import Blueprint, render_template, redirect, url_for, flash, request, abort, jsonify
from flask_login import login_required, current_user
from inc.models import db, JiraApprovalFlow, JiraApprovalStep, AdminDepartment, AdminMember, JiraProject


# 创建蓝图
approval_bp = Blueprint('approval', __name__, url_prefix='/admin/approval')


@approval_bp.route('/flows')
@login_required

def flow_list():
    """审批流程列表"""
    flows = JiraApprovalFlow.query.options(
        db.joinedload(JiraApprovalFlow.department),
        db.joinedload(JiraApprovalFlow.steps)
    ).all()
    return render_template('admin/jira/approval_flow_list.html',
                         flows=flows,
                         JiraProject=JiraProject)


@approval_bp.route('/flow/create', methods=['GET', 'POST'])
@login_required

def create_flow():
    """创建审批流程"""
    departments = AdminDepartment.query.all()
    # 查询所有有效成员，并预加载部门信息
    members = AdminMember.query.filter_by(status=True)\
        .options(db.joinedload(AdminMember.department))\
        .order_by(AdminMember.name).all()
    roles = members  # 保持兼容性

    # 从查询参数获取部门ID
    department_id = request.args.get('department_id', type=int)
    selected_department = None
    if department_id:
        selected_department = AdminDepartment.query.get(department_id)

    if request.method == 'POST':
        # 获取表单数据
        name = request.form.get('name')
        description = request.form.get('description')
        department_id = request.form.get('department_id')
        is_default = request.form.get('is_default') == 'on'

        # 验证
        if not name:
            flash('请填写流程名称', 'danger')
            return render_template('admin/jira/approval_flow_form.html',
                                departments=departments,
                                roles=roles,
                                members=members,
                                flow=None)

        # 检查是否已存在同名的流程
        existing_flow = JiraApprovalFlow.query.filter_by(name=name).first()
        if existing_flow:
            flash('已存在同名的审批流程', 'danger')
            return render_template('admin/jira/approval_flow_form.html',
                                departments=departments,
                                roles=roles,
                                members=members,
                                flow=None)

        # 创建审批流程
        flow = JiraApprovalFlow(
            name=name,
            description=description,
            department_id=department_id if department_id else None,
            is_default=is_default,
            created_at=datetime.now()
        )
        db.session.add(flow)
        db.session.commit()

        # 处理审批步骤
        step_orders = request.form.getlist('step_order')
        step_user_ids = request.form.getlist('step_user_id')
        step_require_comments = []

        # 收集所有需要判断是否要求评论的字段名
        for key in request.form.keys():
            if key.startswith('step_require_comment_'):
                index = key.split('_')[-1]
                step_require_comments.append((index, request.form.get(key) == 'on'))

        # 创建步骤字典，方便查找
        require_comment_dict = {index: require for index, require in step_require_comments}

        # 添加审批步骤
        for i in range(len(step_orders)):
            if not step_user_ids[i]:
                # 如果某个步骤没有审批人，跳过该步骤并给出警告
                flash(f'第{step_orders[i]}步未设置审批人，该步骤将被忽略', 'warning')
                continue

            # 获取当前步骤的要求评论状态，默认False
            require_comment = require_comment_dict.get(str(i), False)

            step = JiraApprovalStep(
                flow_id=flow.id,
                order=int(step_orders[i]),
                user_id=int(step_user_ids[i]),
                require_comment=require_comment
            )
            db.session.add(step)

        db.session.commit()
        flash('审批流程创建成功', 'success')
        return redirect(url_for('approval.flow_list'))

    return render_template('admin/jira/approval_flow_form.html',
                           departments=departments,
                           roles=roles,
                           members=members,
                           flow=None,
                           selected_department=selected_department)


@approval_bp.route('/flow/<int:flow_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_flow(flow_id):
    """编辑审批流程"""
    flow = JiraApprovalFlow.query.get_or_404(flow_id)
    departments = AdminDepartment.query.all()
    roles = AdminMember.query.filter_by(status=True).all()
    members = AdminMember.query.filter_by(status=True).all()

    if request.method == 'POST':
        # 更新流程基本信息
        flow.name = request.form.get('name')
        flow.description = request.form.get('description')
        flow.department_id = request.form.get('department_id')
        flow.is_default = request.form.get('is_default') == 'on'

        # 验证步骤数据
        step_orders = request.form.getlist('step_order')
        step_user_ids = request.form.getlist('step_user_id')
        step_require_comments = request.form.getlist('step_require_comment')

        if not step_orders or len(step_orders) == 0:
            flash('请至少添加一个审批步骤', 'danger')
            return render_template('admin/jira/approval_flow_form.html',
                                flow=flow,
                                departments=departments,
                                members=members)

        # 检查每个步骤是否设置了审批人
        for i in range(len(step_orders)):
            if not step_user_ids[i]:
                flash(f'第{step_orders[i]}步必须设置审批人', 'danger')
                return render_template('admin/jira/approval_flow_form.html',
                                    flow=flow,
                                    departments=departments,
                                    members=members)

        # 验证步骤数据
        if len(step_orders) != len(step_user_ids):
            flash('步骤数据不完整', 'danger')
            return redirect(url_for('approval.flow_detail', flow_id=flow.id))

        # 检查权限
        if not current_user.is_admin and flow.department_id not in [d.id for d in current_user.departments]:
            flash('无权修改该审批流程', 'danger')
            return redirect(url_for('approval.flow_list'))

        try:
            with db.session.begin_nested():  # 使用嵌套事务
                # 删除现有步骤
                for step in flow.steps:
                    db.session.delete(step)

                # 添加新步骤（验证审批人权限）
                for i in range(len(step_orders)):
                    order = int(step_orders[i])
                    user_id = int(step_user_ids[i]) if step_user_ids[i] else None
                    require_comment = request.form.get(f'step_require_comment_{i}') == 'on'

                    # 验证审批人是否有权限
                    if user_id:
                        approver = AdminMember.query.get(user_id)
                        if not approver or not approver.has_permission('REVIEW_PROJECT'):
                            flash(f'用户 {approver.name if approver else user_id} 无审批权限', 'danger')
                            continue

                    step = JiraApprovalStep(
                        flow_id=flow.id,
                        order=order,
                        user_id=user_id,
                        require_comment=require_comment
                    )
                    db.session.add(step)

                # 记录操作日志
                OperationLog.create(
                    admin_id=current_user.id,
                    action='update_approval_flow',
                    resource=f'ApprovalFlow-{flow.id}',
                    details=f'更新审批流程步骤',
                    success=True
                )

            db.session.commit()
            flash('审批流程更新成功', 'success')
            return redirect(url_for('approval.flow_detail', flow_id=flow.id))
        except Exception as e:
            db.session.rollback()
            flash(f'更新审批流程失败: {str(e)}', 'danger')

        return render_template('admin/jira/approval_flow_form.html',
                            flow=flow,
                            departments=departments,
                            members=members)



@approval_bp.route('/flow/<int:flow_id>')
@login_required
def flow_detail(flow_id):
    flow = JiraApprovalFlow.query.options(
        db.joinedload(JiraApprovalFlow.department),
        db.joinedload(JiraApprovalFlow.steps)
            .joinedload(JiraApprovalStep.user)
    ).get_or_404(flow_id)

    # 获取使用此流程的项目
    projects = JiraProject.query.filter_by(approval_flow_id=flow_id).all()

    return render_template('admin/jira/approval_flow_detail.html',
                         flow=flow,
                         projects=projects)


@approval_bp.route('/flow/<int:flow_id>/delete', methods=['POST'])
@login_required

def delete_flow(flow_id):
    """删除审批流程"""
    flow = JiraApprovalFlow.query.get_or_404(flow_id)

    # 检查是否有项目使用此流程
    if JiraProject.query.filter_by(approval_flow_id=flow_id).count() > 0:
        flash('无法删除，已有项目使用此审批流程', 'danger')
        return redirect(url_for('approval.flow_list'))

    # 删除流程及其步骤
    for step in flow.steps:
        db.session.delete(step)

    db.session.delete(flow)
    db.session.commit()

    flash('审批流程已删除', 'success')
    return redirect(url_for('approval.flow_list'))


@approval_bp.route('/api/flows/<int:flow_id>/steps')
@login_required
def get_flow_steps(flow_id):
    """获取审批流程步骤详情(API)"""
    flow = JiraApprovalFlow.query.get_or_404(flow_id)

    steps = []
    for step in flow.steps.order_by(JiraApprovalStep.order).all():
        step_data = {
            'order': step.order,
            'require_comment': step.require_comment
        }

        # 获取审批人信息
        if step.user_id:
            user = AdminMember.query.get(step.user_id)
            if user:
                step_data['user_name'] = user.name
                step_data['user_id'] = user.id

        steps.append(step_data)

    return jsonify(steps)